package com.cmpe.group6.storyroad.ListAdapters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cmpe.group6.storyroad.R;
import com.cmpe.group6.storyroad.Utils;
import com.cmpe.group6.storyroad.jsonClasses.ServerResponseObject;
import com.google.gson.Gson;

/** List adapter for following list.
 *
 */
public class FollowingAdapter extends BaseAdapter {
	Context context;
	List<String> usernames;
	List<String> followers;
	List<Bitmap> profilePictures;

	/**
	 * @param context Current context.
	 * @param usernames Usernames of the followed users.
	 * @param followers Follower count of the followed users.
	 * @param profilePictures Profile pictures of the followed users.
	 */
	public FollowingAdapter(Context context, List<String> usernames,
			List<String> followers, List<Bitmap> profilePictures) {
		this.context = context;
		this.usernames = usernames;
		this.followers = followers;
		this.profilePictures = profilePictures;
	}

	
	/** View Holder class for quicker generation.
	 *
	 */
	private class ViewHolder {
		TextView username;
		TextView followers;
		ImageButton unfollowButton;
		ImageView profilePic;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return this.usernames.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return this.usernames.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		final int pos = position;
		LayoutInflater mInflater = (LayoutInflater) context
				.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.follow_list_item, null);
			holder = new ViewHolder();
			holder.username = (TextView) convertView
					.findViewById(R.id.followings_username);
			holder.followers = (TextView) convertView
					.findViewById(R.id.followings_follower_count);
			holder.unfollowButton = (ImageButton) convertView
					.findViewById(R.id.unfollow_button);
			holder.profilePic = (ImageView) convertView
					.findViewById(R.id.followings_profile_img);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		String username = this.usernames.get(position);
		String followerCount = "Followers: "+this.followers.get(position);
		Bitmap pic = this.profilePictures.get(position);
		holder.unfollowButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new UnfollowTask().execute(pos);
			}
		});
		holder.username.setText(username);
		holder.followers.setText(followerCount);
		holder.profilePic.setImageBitmap(pic);

		return convertView;
	}

	public class UnfollowTask extends AsyncTask<Integer, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			int position = params[0];
			String targetUsername = usernames.get(position);
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Utils.SERVER_NAME + "Unfollow");
			ServerResponseObject responseObject = new ServerResponseObject();

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("request_type",
						"Android"));
				nameValuePairs.add(new BasicNameValuePair("username",
						Utils.username));
				nameValuePairs.add(new BasicNameValuePair("f_username",
						targetUsername));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				String jsonResponse = EntityUtils
						.toString(response.getEntity());
				Gson gson = new Gson();
				responseObject = gson.fromJson(jsonResponse,
						ServerResponseObject.class);

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
			if (responseObject.isUnfollowSuccess()) {
				return true;
			} else {
				return false;
			}
		}

		@Override
		protected void onPostExecute(final Boolean success) {

			if (!success) {
				Toast.makeText(context, "Connection Error", Toast.LENGTH_SHORT)
						.show();
			}
		}

		@Override
		protected void onCancelled() {

		}
	}

}